#coding=utf-8

import json

from tornado.gen    import coroutine, Return
from tornado.log    import access_log as logger

from core.scanner   import ControllerManager
from core.ViewMaker import JsonView
from core.error     import UserError
from utils.jwter    import JwtGenerator

from pojo.json.JsonMsg import MsgMaker

from services.organ import api
from .tools import name_pwd_validator


@ControllerManager.register(r'/api/profile', ('get'))
@coroutine
def get_org_profile(req):
    try:
        user_id = req.get_argument('user_id')

        if not user_id:
            raise UserError('request user id is null')

        ret, msg = api.get_org_info(user_id)

        if not ret:
            raise UserError(msg)

    except UserError as e:
        logger.error('%s:%s' % (e.__class__.__name__, e.message))
        raise Return(JsonView(MsgMaker.badMsg(e.message)))  # 返回错误信息

    raise Return(JsonView(MsgMaker.goodMsg(data = ret)))  # 返回

@ControllerManager.register(r'/api/profile/save', ('post'))
@coroutine
def save_org_profile(req):
    try:
        req_body = json.loads(req.get_body())
        ret, msg = api.save_org_info(req_body)

    except UserError as e:
        logger.error('%s:%s' % (e.__class__.__name__, e.message))
        raise Return(JsonView(MsgMaker.badMsg(e.message)))  # 返回错误信息

    raise Return(JsonView(MsgMaker.goodMsg()))  # 返回


